package com.cy.deepseeksport.aiService;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import dev.langchain4j.web.search.WebSearchInformationResult;
import dev.langchain4j.web.search.WebSearchOrganicResult;
import dev.langchain4j.web.search.WebSearchRequest;
import dev.langchain4j.web.search.WebSearchResults;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Value;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class BochaApi {

    @Value("${deepseek.search-api-key}")  // 从配置文件中读取API Key
    private String bochaApiKey;

    @Resource
    private ObjectMapper objectMapper;

    @Resource
    private RestTemplate restTemplate;



    public WebSearchResults search(String searchKeyword) {
        try {
            // 构建请求体
            JSONObject requestBody = new JSONObject();
            requestBody.put("query", searchKeyword);
            requestBody.put("freshness", "noLimit");
            requestBody.put("summary", true);
            requestBody.put("count", 50);

            // 发送请求
            java.net.http.HttpRequest httpRequest = java.net.http.HttpRequest.newBuilder()
                    .uri(URI.create("https://api.bochaai.com/v1/web-search"))
                    .header("Content-Type", "application/json")
                    .header("Authorization", "Bearer " + bochaApiKey)
                    .POST(HttpRequest.BodyPublishers.ofString(requestBody.toJSONString()))
                    .build();

            HttpClient httpClient = HttpClient.newBuilder().build();
            HttpResponse<String> response = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());

            if (response.statusCode() != 200) {
                throw new RuntimeException("HTTP request failed with status: " + response.statusCode());
            }

            // 解析响应
            JSONObject jsonResponse = JSON.parseObject(response.body());
            int code = jsonResponse.getIntValue("code");
            if (code != 200) {
                throw new RuntimeException("Search failed with code: " + code + ", message: " + jsonResponse.getString("msg"));
            }

            // 提取搜索结果
            List<WebSearchOrganicResult> results = new ArrayList<>();
            JSONObject data = jsonResponse.getJSONObject("data");
            if (data != null) {
                JSONObject webPages = data.getJSONObject("webPages");
                if (webPages != null) {
                    List<JSONObject> pages = webPages.getJSONArray("value").toJavaList(JSONObject.class);
                    for (JSONObject page : pages) {
                        results.add(WebSearchOrganicResult.from(
                                page.getString("name"),
                                URI.create(page.getString("url")),
                                page.getString("snippet"),
                                page.getString("summary")
                        ));

                    }
                }
            }

            // 构建搜索信息
            long totalResults = 0;
            if (data != null && data.getJSONObject("webPages") != null) {
                totalResults = data.getJSONObject("webPages").getLongValue("totalEstimatedMatches");
            }
            WebSearchInformationResult searchInformation = WebSearchInformationResult.from(totalResults);

            // 构建元数据
            Map<String, Object> metadata = new HashMap<>();
            metadata.put("logId", jsonResponse.getString("log_id"));
            if (data != null && data.getJSONObject("queryContext") != null) {
                metadata.put("originalQuery", data.getJSONObject("queryContext").getString("originalQuery"));
            } else {
                metadata.put("originalQuery", searchKeyword);
            }

            return WebSearchResults.from(metadata, searchInformation, results);
        } catch (Exception e) {
            throw new RuntimeException("Failed to perform search", e);
        }
    }

}